<?php
require "../common/user_online.php";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>EbookAZ</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<?php require "../components/head.php" ?>
</head>
<body onload="MakeCurrentPage(1)">
<div id="container">
	<?php require "../components/user_menu.php" ?>
	<?php require "../components/user_header.php" ?>
	<div id="content">
		<?php require "../components/content_left.php"?>
		<div id="content_right" align="center">
		<?php
		include "../common/db.inc";
		$userid = $_SESSION['user_id'];
		
		$mysqli = new mysqli($host, $username, $password,$dbname);
		$mysqli->set_charset('utf8');	
		/* check connection */
		if (mysqli_connect_errno()) {
		    printf("Connect failed: %s\n", mysqli_connect_error());
		    exit();
		}
		
		if($_POST['txtPassword1'] == "")
			$pass = $mysqli->real_escape_string($_POST['txtOldPassword']);
		else
			$pass = $mysqli->real_escape_string($_POST['txtPassword1']);
			
		$pass = md5($pass);
		$email = $mysqli->real_escape_string($_POST['txtEmail']);
		$fields = $mysqli->real_escape_string($_POST['checkbox']);
		
		$sql = "CALL sp_UpdateUserInfo($userid,'$pass','$email')";
		@$mysqli->query($sql);

		if ($mysqli->errno) 
		{
			die($mysqli->errno.": ".$mysqli->error);
			$mysqli->close();
			exit();
		}
		
		deleteOldInterest($userid);
		if(count($fields) > 0)
		{
			foreach($fields as $field)
			{
				addInterest($userid,$field);
			}//end foreach
		}//end if
		
		echo "<p>Cập nhật thành công!";
		echo "<a href='../user/home.php'>Trở về trang chủ</a></p>";
		?>
		</div>
	</div>
	<?php require "../components/footer.php" ?>
</div>
</body>
</html>

<?php
function deleteOldInterest($userid)
{
	include "../common/db.inc";
	$mysqli = new mysqli($host,$username,$password,$dbname);
	$mysqli->set_charset("utf8");
	if(mysqli_connect_errno())
	{
		die('Kết nối thất bại:'. mysqli_connect_error());
		exit();
	}//end if
	
	$sql = "CALL sp_DeleteInterest($userid)";
	$mysqli->query($sql);
	if($mysqli->errno)
	{
		die($mysqli->error);
	}

	$mysqli->close();
}//end function deleteOldInterest

function addInterest($userid,$field)
{
	include "../common/db.inc";
	$mysqli = new mysqli($host,$username,$password,$dbname);
	$mysqli->set_charset("utf8");
	if(mysqli_connect_errno())
	{
		die('Kết nối thất bại:'. mysqli_connect_error());
		exit();
	}//end if
	
	$sql = "CALL sp_AddInterest($userid,$field)";
	$result = $mysqli->query($sql);
	if ($mysqli->errno) 
	{
		die("Lỗi:".$mysqli->errno.$mysqli->error);
	}//end if

	$mysqli->close();
}//end function addInterest
?>